﻿_.templateSettings.interpolate = /{([\s\S]+?)}/g;
$(function () {

    /**  TODO input输入限制**/
    $(document).on('input','input[pattern]',function (e) {
        var $this = $(this);
        var pattern = $this.attr('pattern');
        pattern = pattern.slice(1,pattern.length - 1);
        var reg = new RegExp(pattern,'g');
        var value = $this.val();
        value = value.replace(reg,'');
        var decimal = $this.attr('float');

        if(decimal !== undefined){
            var decimalIndex = value.indexOf('.');
            if(~decimalIndex){
                if(!decimalIndex){
                    value = '';
                }else{
                    var decimalStr = value.replace(/[^\.]/g,'');
                    while(decimalStr.length > 1){
                        value = value.slice(0,value.length - 1);
                        decimalStr = value.replace(/[^\.]/g,'');
                    }

                    var firstIndex = value.indexOf('.');
                    value = value.slice(0,firstIndex + ((parseInt(decimal) || 2) + 1));
                }
            }
        }
        $this.val(value);
    })

    //日期
    $('.date-choose').datetimepicker({
        language:  'zh-CN',
        autoclose : true,
        minView : 2,
        format : 'yyyy/mm/dd',
        todayBtn:  1,
        pickerPosition:'bottom-left'//日期插件弹出的位置
    });
    //checkedbox  联动

    /**
     *  备注   所有需要联动的  都加上 link-age 属性 值任意写 但是总开关和子开关一定要保持一致 代表是哪一组的
     *  总开关 加上  is-parent 属性   不用写任何值  子开关加上 is-sub属性
     *
     *  例子   总开关  input link-age=aa is-parent
     *        子开关  input link-age=aa is-sub
     * **/
    $(document).on('change','input[type="checkbox"][link-age]',function () {
        var $this = $(this),
            isParent = $this.attr('is-parent') !== undefined,
            flagName = $this.attr('link-age'),
            $allSub = $('input[type="checkbox"][is-sub][link-age="'+flagName+'"]'),
            isChecked = this.checked,
            subLen = $allSub.length,
            $parent = $('input[type="checkbox"][is-parent][link-age="'+flagName+'"]');
        if(isParent){
            $allSub.prop('checked',isChecked);
        }else{
            var checkedList = _.filter($allSub,function (ele,index) {
                return ele.checked;
            })
            $parent.prop('checked',checkedList.length === subLen);
        }
    })

    /**TODO remarks-input  备注input失去焦点事件**/


    $(document).on('blur','input[remarks-input]',function () {
        var $this= $(this),
            orderId = $this.attr('order-id');
        if(!orderId)return;
        scmapi && scmapi.updateRemark({
            remark : this.value,
            orderId : orderId
        })
    })


    /**TODO  input数量限制**/
    $(document).on('input','input[input-max]',function () {
        var $this = $(this);
        var maxNum = parseInt($this.attr('max-num')) || 0;
        var value = parseInt($this.val())
        if(value){
            if(value > maxNum){
                this.value = maxNum;
                $this.trigger('input');
            }
        }
    })

})

;(function (w,$) {
    /** TODO 数组扩展**/
    $.extend(String.prototype,{
        isPhone : function () {
            return /[^\D-]/.test(this);
        },
        isEmail : function () {
            return true;
        },
        isCode : function () {
            return !/[^a-z\d]/i.test(this);
        },
        substitute: function(data) {
            if (data && typeof(data) == 'object') {
                return this.replace(/\{([^{}]+)\}/g, function(match, key) {
                    var value = data[key];
                    return (value !== undefined) ? '' + value: '';
                });
            } else {
                return this.toString();
            }
        },
    })

    $.extend({
        getUrlParam : function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })
    $.fn.extend({
        //乘法
        multiplication : function () {
            return _.reduce(this,function (pre,cur) {
                return pre *= parseFloat((cur.tagName.toLocaleLowerCase() === 'input' ? $(cur).val() :$(cur).html()).trim()) || 0
            },1).toFixed(2)
        },
        createOptions : function (list,options) {
            options = options || {};
            var tmp = '<option value="{'+options.value+'}">{'+options.label+'}</option>';
            if(list.length){
                this.html('').append((function () {
                    return _.map(list,function(item,index){
                        return tmp.substitute(item);
                    }).join('');
                }()))
            }
            return this;
        },
        getOptionsInfo : function () {
            var text = this.find("option:selected").text();
            var value = this.val();
            return {
                value : value ? value : '',
                text : (value && value !== '0') ? text : '',
            }
        }
    })

    var _getvVal = function _getvVal(obj) {
        var isInput = /input|textarea/.test(obj.tagName.toLocaleLowerCase())
        return isInput ? $(obj).val() : $(obj).html();
    }

    /** TODO 输入框统计 **/

    var AddSumCreator = function AddSumCreator(options) {
        var _this = this;
        this.eventName = 'input.xxxxx' + String(Math.random()).replace('.','');
        this.$root = options.root;
        this.$input = options.$input || $();
        this.reckon = options.reckon || '+';
        this.decimal = options.decimal === undefined ? 2 : options.decimal;
        this.total = 0;
        this.callBackListen = null;//监听的回调函数
        this.openListen = false;//是否开启过监听
        if(!this.$root)throw Error('没有根元素，无法计算');
        this.bindEvent();
        this.$root.on('addSum',function (e,sum) {
            sum = sum.toFixed(_this.decimal);
            if(/input|textarea/.test(e.target.tagName.toLocaleLowerCase())){
                _this.$root.val(sum);
            }else{
                _this.$root.html(sum);
            }
            _this.total = parseFloat(sum);
            _this.callBackListen && _this.callBackListen();
        })
    }

    //绑定事件
    AddSumCreator.prototype.bindEvent = function () {
        var _this = this;
        _this.$input.bind(this.eventName,function () {
            _this.census();
        })

    }
    //加法
    AddSumCreator.prototype.addition = function () {
        var sum = 0;
        this.$input.each(function (index,ele) {
            sum = _.add(sum, parseFloat(_getvVal(ele)) || 0);
        })
        this.$root.trigger('addSum',sum);
    }

    //获取输入框的总值
    AddSumCreator.prototype.census = function () {
        if(this.reckon === '+'){
            this.addition();
        }
        if(this.reckon === '*'){
            this.multiplication();
        }
    }
    //乘法
    AddSumCreator.prototype.multiplication = function () {
        var sum = 1;
        this.$input.each(function (index,ele) {
            sum = _.multiply(sum, parseFloat(_getvVal(ele)) || 0);
        })
        this.$root.trigger('addSum',sum);
    }
    //更新
    AddSumCreator.prototype.update = function ($input) {
        this.$input = $input || this.$input;
        if($input){
            this.$input.unbind(this.eventName);
            this.bindEvent();
        }
        this.census();
        return this;
    }
    AddSumCreator.prototype.add = function ($input) {
        this.$input.push($input)
        this.update(this.$input);
    }
    AddSumCreator.prototype.slice = function (index) {
        this.$input.splice(index,1);
        this.update(this.$input);
    }
    AddSumCreator.prototype.listen = function (fn) {
        this.callBackListen = fn;
        this.openListen = true;
    }
    //计算 AddSumCreator这个函数计算总和的总和
    function TotalSumCreator(options) {
        this.totals = options.totals || [];
        this.root = options.root || $();
        this.addListen();
    }
    //监听
    TotalSumCreator.prototype.addListen = function () {
        var _this = this;
        $.each(this.totals,function (i,addSum) {
            !addSum.openListen && addSum.listen(function () {
                _this.addition();
            })
        })
    }
    //加法计算
    TotalSumCreator.prototype.addition = function () {
        var sum = _.sum(_.map(this.totals, function(el) {
            return el.constructor === AddSumCreator ? el.total : 0;
        }));
        this.root[this.root[0].tagName.toLocaleLowerCase() === 'input' ? 'val' : 'html'](sum.toFixed(2));
    }
    //删除
    TotalSumCreator.prototype.slice = function (index) {
        this.totals.splice(index,1);
        this.update();
    }
    //添加
    TotalSumCreator.prototype.add = function (addSum) {
        this.totals.push(addSum);
        this.update();
    }
    //更新
    TotalSumCreator.prototype.update = function (list) {
        if(list){
            this.totals = list;
        }
        this.addListen();
        this.addition();
        return this;
    }
    $.extend(w,{
        log : function () {
            console.log.apply(console,arguments);
        },
        AddSumCreator : AddSumCreator,
        TotalSumCreator : TotalSumCreator,
        showLoading : function () {
            layer && layer.load(1, {
                shade : [ 0.5, '#fff' ]
            });
        },
        _ajax : function _ajax(option) {
            var _defaultsetting = {
                type: "GET",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                async: true, // 同步  true 异步。默认是异步
                dataType: 'json',
                error : function () {
                    layer && layer.closeAll && layer.closeAll();
                }
            }
            return $.ajax($.extend(_defaultsetting,option || {}));
        },
        scmapi : (function () {
            var domainUrl = '';

            var operationLogTr = [
                '<tr>',
                '    <td><span>{operatorUserName}</span></td>',
                '    <td><span>{operationProject}</span></td>',
                '    <td><span>{formatTime}</span></td>',
                '    <td><span>{remark}</span></td>',
                '</tr>'
            ].join('')


            var operationLog = function operationLog(data) {
                var $operationLog = $('#operationLog');
                var operationLogUrl = domainUrl + '/so/common/gethis';
                showLoading();
                $operationLog.html('');
                _ajax({
                    url : operationLogUrl,
                    data : $.param(data || {}),
                    success : function (result) {
                        layer.closeAll();
                        if(result.returnCode === '0000'){
                            var items = result.items || [];
                            $operationLog.html((function () {
                                return items.length ? _.map(items,function (item) {
                                    return operationLogTr.substitute($.extend({
                                        formatTime : moment(item.operationTime).format('YYYY-MM-DD  HH:mm:ss')
                                    },item))
                                }).join('') : '';
                            }()))
                        }
                    }
                })

                return scmapi;
            }
            
            var updateRemark = function updateRemark(data) {
                var remarksUrl = domainUrl + '/so/common/updateremark';
                showLoading();
                _ajax({
                    url : remarksUrl,
                    data : $.param(data || {}),
                    success : function (result) {
                        log('result',result);
                        layer.closeAll();
                    }
                })

                return scmapi;
            }


            var updateedits = function updateedits(url,data) {
                var update4Url = domainUrl +  url;
                showLoading();
                _ajax({
                    url : update4Url,
                    data : $.param(data || {}),
                    success : function (result) {
                        log('result',result);
                        layer.closeAll();
                    }
                })

            }

            return {
                operationLog:operationLog,
                updateRemark : updateRemark,
                updateedits : updateedits,
                init : function (base) {
                    domainUrl = base || '';
                    return scmapi;
                }
            }

        }()),

    })

}(window,jQuery));

